#! /usr/bin/env python
# -*- coding: utf-8 -*-

import time
import os
import re
import random
import pycurl
import StringIO

import FileHostProtoType


class gusitem(FileHostProtoType.HostItem):
    def __init__(self, name, type, code, link='', encrypt_name='', server_name=''):
        FileHostProtoType.HostItem.__init__(self, name, type, code, link, encrypt_name, server_name)
    
class glumbouploads(FileHostProtoType.FileHostProcess):            
    def __init__(self, user, pwd):
        FileHostProtoType.FileHostProcess.__init__(self)
        self.hostname = "GlumboUploads" 
        self._opener = None
        self._user = user
        self._pwd = pwd
        self.islogin = False

            
    def login(self):
        if self.islogin:
            return True
        #build opener
        self.generateOpener()
        self.fherr.write('login to GlumboUploads %s/%s...'%(self._user,'*'*len(self._pwd)))
        loginData = {'login' : self._user, \
                'password' : self._pwd,
                'op' : 'login',
                'redirect':'',
                'x':'0',
                'y':'0'}
        response = self.loginFileHost("http://glumbouploads.com/", loginData)
        
        # user info can be found in cookie
        if self._user.lower() not in response.lower():
            self.fherr.write("User %s Failed to Login DepositFiles." % self._user)
            return False
        self.fherr.write("User %s logined." % self._user)
        self.islogin = True
        return True
    
    def find(self, filenames = [], filelist = None):
        found = []
        if filelist == None:
            return found      
        filelistlower = [fl.name.lower() for fl in filelist]
        todel = []
        for fl in filenames:
            try:
                index = filelistlower.index(os.path.basename(fl).lower())
                found.append(filelist[index])
                todel.append(fl)
            except:
                continue
        for d in todel:
            filenames.remove(d)
        found.sort()
        return found
        
    def getFileList(self):
        return []
    
    def get_upload_key(self, content, key, index, sed='"'):
        lines = content.split('\n')
        for line in lines:
            if key in line:
                tokens = line.split(sed)
                value = tokens[index]
                return value
        return ''
    
    def upload_web(self, file, progressLog=None, other_args=None):
        #indexpage        
        get_upload_info_url = 'http://glumbouploads.com/'
        get_upload_info_page = self.post_request(get_upload_info_url).encode('utf8','ignore')
        
        srv_tmp_url = self.get_upload_key(get_upload_info_page, 'name="srv_tmp_url"', -2)
        sess_id = self.get_upload_key(get_upload_info_page, 'name="sess_id"', -2)
        
        
        uid = str(random.randint(1000,9999))
        uid += str(random.randint(1000,9999))
        uid += str(random.randint(1000,9999))
        upload_link = self.get_upload_key(get_upload_info_page, 'name="file"', -6)
        upload_link = "%s%s&js_on=1&utype=reg&upload_type=file&convert=no" % (upload_link, uid)
        print srv_tmp_url, sess_id
        
        data = {"sess_id":sess_id,
                "srv_tmp_url":srv_tmp_url,
                "upload_type":"file",
                "convert":"no",
                "file_0_descr":"",
                "file_0_public":'1',
                "tos":'1',
                "link_rcpt":"",
                "link_pass    ":"",
                "submit_btn":"Upload!",
                "file_0":open(file, 'rb')}
        self.fherr.write("Uploading...%s" % file)
        
        callback = None
        if progressLog is not None:
            callback = progressLog.write
        result = self.post_file(upload_link, data, self.get_cookies(), callback=callback)
        #result
        print result
        if not "<textarea name='st'>OK</textarea>" in result:
            self.fherr.write(result)
            self.fherr.write("orz:" + upload_link)
            self.fherr.write("Failed to upload %s" % file)
            time.sleep(300)
            return

        code = self.get_upload_key(result, 'OK', 1, sed="<textarea name='fn'>")
        code = code[0:code.find("</textarea>")]
        link = "http://glumbouploads.com/%s" % code
        item = gusitem(os.path.basename(file), 'file', code, link, self.rename_func(file))
        self.newupload.append(item)
        self.fhout.write(item.format()) 
        return item